# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE


def exe_remote_cmd(user, host, cmd):
    """
    execute command on remote host
    :param user:  remote user
    :param host:  remote host
    :param cmd: command executed in remote
    :return: stdout and stderr
    """
    return Popen(['ssh', '{}@{}'.format(user, host), cmd], stdout=PIPE).communicate()


def exe_local_simple_cmd(cmd):
    """
    execute a command in local
    :param cmd: command
    :return: stdout and stderr
    """
    return Popen(cmd.split(), stdout=PIPE).communicate()


def exe_local_cmd_pipe(*cmds):
    """
    execute command with pipe
    :param cmds: commands 
    :return: stdout and stderr
    """
    if len(cmds) == 0:
        return None, None
    elif len(cmds) == 1:
        return exe_local_simple_cmd(cmds[0])
    else:
        pouts = []
        pouts.append(Popen(cmds[0].split(), stdout=PIPE))
        idx = 1
        while idx < len(cmds):
            pouts.append(Popen(cmds[idx].split(), stdout=PIPE, stdin=pouts[idx - 1].stdout))
            idx += 1
        return pouts[-1].communicate()
